<template>
  <div
    class="cart-item-wrapper"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
  >
    <!-- 滑动内容层 -->
    <div class="cart-item-container" :style="{ transform: `translateX(${translateX}px)` }">
      <el-card shadow="hover" class="cart-item">
        <el-row :gutter="12">
          <el-col :xs="8" :sm="8" :md="8">
            <img
              v-if="img && !imageLoadError"
              :src="img"
              class="item-img"
              @error="handleImageError"
            />
            <div v-else class="image-placeholder">
              <el-icon :size="20" color="#C0C4CC">
                <Picture />
              </el-icon>
            </div>
          </el-col>

          <el-col :xs="16" :sm="16" :md="16">
            <div class="item-info">
              <div class="title">{{ title }}</div>
              <div class="price">
                <span class="origin">￥{{ originPrice }}</span>
                <span class="current">￥{{ currentPrice }}</span>
              </div>
              <div class="specs">{{ specs.join('，') }}</div>
              <div class="stepper">
                <el-input-number v-model="localCount" :min="1" :max="max" />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 删除按钮 -->
    <div class="delete-button" @click="onDelete">
      <el-button type="danger" size="small" round>删除</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { Picture } from '@element-plus/icons-vue'

interface Props {
  img: string
  title: string
  originPrice: number
  currentPrice: number
  specs: string[]
  modelValue: number
  max?: number
  cartId: number
}

const props = withDefaults(defineProps<Props>(), { max: 999 })
const emit = defineEmits(['update:modelValue', 'delete'])

const imageLoadError = ref(false)
const translateX = ref(0)
const startX = ref(0)
const startY = ref(0)
const isSliding = ref(false)
const isHorizontalSlide = ref(false)

// 重置当前项的滑动状态
const resetSlide = () => {
  translateX.value = 0
}

// 图片加载错误处理
const handleImageError = () => {
  imageLoadError.value = true
}

const localCount = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 删除事件
const onDelete = () => {
  emit('delete', props.cartId)
  resetSlide()
}

// 触摸开始
const handleTouchStart = (e: TouchEvent) => {
  startX.value = e.touches[0].clientX
  startY.value = e.touches[0].clientY
  isSliding.value = true
  isHorizontalSlide.value = false
}

// 触摸移动
const handleTouchMove = (e: TouchEvent) => {
  if (!isSliding.value) return

  const currentX = e.touches[0].clientX
  const currentY = e.touches[0].clientY
  const deltaX = currentX - startX.value
  const deltaY = currentY - startY.value

  // 判断是否为水平滑动（水平移动距离大于垂直移动距离）
  if (!isHorizontalSlide.value && Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 10) {
    isHorizontalSlide.value = true
  }

  if (isHorizontalSlide.value) {
    e.preventDefault()
    // 限制只能向左滑动，最大滑动距离为80px（删除按钮宽度）
    translateX.value = Math.min(0, Math.max(deltaX, -80))
  }
}

// 触摸结束
const handleTouchEnd = () => {
  if (!isSliding.value || !isHorizontalSlide.value) {
    resetSlide()
    return
  }

  isSliding.value = false
  isHorizontalSlide.value = false

  // 如果滑动距离超过阈值（按钮宽度的50%），则显示删除按钮
  if (Math.abs(translateX.value) > 40) {
    translateX.value = -80
  } else {
    resetSlide()
  }
}

// 点击其他区域关闭删除按钮
const handleClickOutside = (e: MouseEvent) => {
  const target = e.target as HTMLElement
  const wrapper = target.closest('.cart-item-wrapper')
  if (!wrapper) {
    resetSlide()
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.cart-item-wrapper {
  position: relative;
  margin-bottom: 12px;
  overflow: hidden; /* 关键：隐藏超出部分 */
  touch-action: pan-y; /* 允许垂直滚动 */
}

.cart-item-container {
  position: relative;
  z-index: 1; /* 确保在删除按钮上方 */
  background-color: #fff; /* 关键：添加背景色遮住按钮 */
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* 优化动画曲线 */
}

.cart-item {
  margin-bottom: 0;
  border-radius: 8px; /* 添加圆角提升视觉效果 */
}

.item-img {
  width: 100px;
  height: 100px;
  aspect-ratio: 1 / 1;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}

.image-placeholder {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  height: 100%;
}

.title {
  font-size: 15px;
  font-weight: 600;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price .origin {
  font-size: 13px;
  color: #999;
  text-decoration: line-through;
  margin-right: 6px;
}

.price .current {
  font-size: 17px;
  color: #f56c6c;
  font-weight: bold;
}

.specs {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stepper {
  margin-top: auto;
  align-self: flex-end;
}

/* 删除按钮样式 */
.delete-button {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 80px;
  z-index: 0; /* 确保在内容层下方 */
  background-color: #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 点击删除按钮时的反馈效果 */
.delete-button:active {
  background-color: #e45656;
}
</style>
